package com.github.catvod.spider;

import android.content.Context;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.net.OkHttp;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: fs
 * 欢乐谷爬虫
 * @date: 2025/1/15
 */
public class Huanlegu extends Spider {
    private String siteUrl="https://5.hlg4846a.cc:8888/";
    private final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";



    // 进行获取最新域名
    public String get_filed(){
        String[] url_list=new String[]{"https://5.hlg4905a.cc","https://5.hlg4846a.cc:8888/","https://5.hlg4701a.cc/","https://5.hlg4702a.cc"};
        // 随机进行获取一个URl
        for (int i = 0; i < url_list.length; i++) {
            String html = OkHttp.string(url_list[i], getHeader());
            Document doc = Jsoup.parse(find(html));
            if (!doc.select(".flag").isEmpty()){
                // 进行获取域名
                Elements select = doc.select(".field #as");
                System.out.println(select);
                if (!select.isEmpty()){
                    // 进行随机获取一个元素
                    Random random = new Random();
                    int randomIndex = random.nextInt(select.size());
                    siteUrl = select.get(randomIndex).attr("href");
                    Notice.show("自动获取到新域名");
                    SpiderDebug.log("获取到最新域名："+siteUrl);
                    break;
                }
            }
        }
        return null;
    }

    @Override
    public void init(Context context) throws Exception {
        // 进行域名初始化
        get_filed();
        super.init(context);
    }

    private Map<String, String> getHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        headers.put("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers.put("cache-control", "no-cache");
        headers.put("pragma", "no-cache");
        headers.put("priority", "u=0, i");
        headers.put("sec-ch-ua-mobile", "?0");
        headers.put("sec-ch-ua-platform", "\"Windows\"");
        headers.put("sec-fetch-dest", "document");
        headers.put("sec-fetch-mode", "navigate");
        headers.put("sec-fetch-site", "none");
        headers.put("sec-fetch-user", "?1");
        headers.put("upgrade-insecure-requests", "1");
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");
        return headers;
    }

    private String find(String html) {
        String regex = "<script>document.write\\(decodeURIComponent\\((.*)\\)\\)</script>";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(html);
        if (m.find()){
            SpiderDebug.log("获取到数据");
            // 进行URL解码
            return URLDecoder.decode(m.group(1));
        }else{
            SpiderDebug.log("没有找到html网页数据哦~");
            return null;
        }
    }

    /**
     * 解析html获取视频列表
     * @param doc
     * @return
     */
    private List<Vod> parseHtml(Document doc) {
        List<Vod> videos = new ArrayList<>();
        Elements vod_item_list = doc.select(".list-container .vod-list");
        for (Element vod_list : vod_item_list) {
            Elements list = vod_list.select(".vod-item");
            for (Element element : list) {
                String url=element.select(".vod-img").attr("href");
                String title=element.select(".vod-title").text();
                String pic=element.select(".vod-img img").attr("data-original");
                videos.add(new Vod(url,title,pic));
            }
        }
        return videos;
    }

    /**
     * 首页内容
     * @param filter 暂时不用
     * @return
     * @throws Exception
     */
    @Override
    public String homeContent(boolean filter) throws Exception {
        List<Class> classes = new ArrayList<>();
        List<String> typeIds = Arrays.asList("/", "/category/1", "/category/2", "/category/3", "/category/4", "/category/5", "/category/31", "/category/29", "/category/6", "/category/7", "/category/35", "/category/36", "/category/37", "/category/10", "/category/11", "/category/12", "/category/19", "/category/20", "/category/23", "/category/30", "/category/28");
        List<String> type_name = Arrays.asList("首页", "大陆", "日韩", "欧美", "动漫", "综艺", "AI脱衣", "成人游戏", "国产传媒", "偷拍自拍", "绿帽偷情", "JK萝莉", "强奸迷奸", "日韩无码", "中文字幕", "日韩杂类", "欧美无码", "黑白专区", "少女动漫", "网爆黑料", "其他综艺");
        for (int i = 0; i < typeIds.size(); i++) {
            classes.add(new Class(typeIds.get(i), type_name.get(i)));
        }
        String html = OkHttp.string(siteUrl, getHeader());
        if (html!=null){
            SpiderDebug.log("获取到数据");
            String html_str = find(html);
            Document doc = Jsoup.parse(html_str);
            List<Vod> list = parseHtml(doc);
            return Result.string(classes, list);
        }else {
            Notice.show("请求失败了!");
            return Result.error("请求失败了!");
        }
    }

    /**
     * 分类
     * @param tid    影片分类id值，来自 homeContent 里面的 type_id 值
     * @param pg     第几页
     * @param filter 暂时不用
     * @param extend 用户已经选择的二级筛选数据
     * @return
     * @throws Exception
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        // 进行判断是否是首页
        String categoryUrl="";
        if (tid.equals("/")){
            categoryUrl=siteUrl;
        }else{
            tid=tid.substring(1);
            categoryUrl=siteUrl+tid+"/"+pg+"/";
        }
        System.out.println(categoryUrl);
        String html = OkHttp.string(categoryUrl, getHeader());
        String html_str = find(html);
        Document html_doc = Jsoup.parse(html_str);
        List<Vod> list = parseHtml(html_doc);
        Integer total = (Integer.parseInt(pg) + 1) * 30;
        return Result.string(Integer.parseInt(pg), Integer.parseInt(pg) + 1, 10, total, list);
    }

    /**
     * 详情
     * @param ids ids.get(0) 来源于 categoryContent() 或 searchContent() 的 vod_id
     * @return
     * @throws Exception
     */
    @Override
    public String detailContent(List<String> ids) throws Exception {
        String id=ids.get(0);
        if (id.startsWith("/")){
            id=id.substring(1);
        }
        System.out.println(id);
        String detailUrl = siteUrl + id;
        String string = OkHttp.string(detailUrl, getHeader());
        String html_str = find(string);
        Document doc = Jsoup.parse(html_str);
        // 获取视频信息
        String title = doc.select(".vod-header").text();
        // 进行匹配封面
        String regex_m3u8 = "var url = \"(.*)\"";
        String regex_pic = "var poster = \"(.*)\"";
        Pattern pattern = Pattern.compile(regex_pic);
        Matcher m = pattern.matcher(html_str);
        String pic = m.find() ? m.group(1) : "";
        // 进行匹配播放m3u8
        pattern = Pattern.compile(regex_m3u8);
        m = pattern.matcher(html_str);
        String m3u8 = m.find() ? m.group(1) : "";
        Vod vod = new Vod();
        vod.setVodId(id);
        vod.setVodName(title);
        vod.setVodPic(pic);
        vod.setVodPlayFrom("hlg");
        vod.setVodPlayUrl("播放$"+m3u8);
        return Result.string(vod);
    }

    /**
     * 第一页搜索
     * @param key   关键字/词
     * @param quick 暂时不用
     * @return
     * @throws Exception
     */
    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        return search(key,"1");
    }

    /**
     * 后续分页搜索翻页
     * @param key   关键字/词
     * @param quick 暂时不用
     * @param pg    第几页
     * @return
     * @throws Exception
     */
    @Override
    public String searchContent(String key, boolean quick, String pg) throws Exception {
        return search(key,pg);
    }

    public String search(String key, String pg) throws Exception {
        String searchUrl=siteUrl+"search/"+ URLEncoder.encode(key)+"/"+pg+"/";
        System.out.println(searchUrl);
        String html = OkHttp.string(searchUrl, getHeader());
        String html_str = find(html);
        if (html_str != null && html_str.isEmpty()) {
            return Result.error("解析数据为null");
        }
        Document doc = Jsoup.parse(html_str);
        List<Vod> list = parseHtml(doc);
        return Result.string(Integer.parseInt(pg), Integer.parseInt(pg) + 1, 10, list.size(), list);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).header(getHeader()).string();
    }
}
